import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

/**
 * 游戏主控工具
 * 支持游戏主控Agent的所有核心操作
 */
export const gameMasterTool = createTool({
  id: 'game-master',
  description: '游戏主控工具，负责统一管理游戏流程、协调Agent、维护状态',
  inputSchema: z.object({
    action: z.enum([
      'start_game',
      'manage_session', 
      'coordinate_agents',
      'update_state',
      'handle_error',
      'get_status',
      'pause_game',
      'resume_game',
      'end_game'
    ]).describe('要执行的操作类型'),
    
    // 游戏配置参数
    gameConfig: z.object({
      difficulty: z.enum(['easy', 'normal', 'hard']).optional(),
      theme: z.string().optional(),
      suspectCount: z.number().optional(),
      playerProfile: z.any().optional()
    }).optional().describe('游戏配置'),
    
    // 会话管理参数
    sessionId: z.string().optional().describe('游戏会话ID'),
    
    // Agent协调参数
    targetAgent: z.string().optional().describe('目标Agent类型'),
    operation: z.string().optional().describe('要执行的操作'),
    
    // 状态更新参数
    updates: z.any().optional().describe('状态更新数据'),
    
    // 错误处理参数
    error: z.string().optional().describe('错误信息'),
    context: z.any().optional().describe('错误上下文'),
    
    // 通用参数
    params: z.any().optional().describe('其他操作参数'),
    data: z.any().optional().describe('操作数据'),
    timestamp: z.string().optional().describe('时间戳')
  }),
  outputSchema: z.object({
    success: z.boolean().describe('操作是否成功'),
    message: z.string().describe('操作结果消息'),
    data: z.any().optional().describe('返回的数据'),
    gameState: z.any().optional().describe('游戏状态'),
    sessionInfo: z.any().optional().describe('会话信息'),
    nextActions: z.array(z.string()).optional().describe('建议的下一步操作'),
    error: z.string().optional().describe('错误信息')
  }),
  execute: async ({ context }) => {
    const { action, ...params } = context;
    
    try {
      console.log(`游戏主控工具执行操作: ${action}`, params);
      
      switch (action) {
        case 'start_game':
          return await handleStartGame(params);
          
        case 'manage_session':
          return await handleManageSession(params);
          
        case 'coordinate_agents':
          return await handleCoordinateAgents(params);
          
        case 'update_state':
          return await handleUpdateState(params);
          
        case 'handle_error':
          return await handleError(params);
          
        case 'get_status':
          return await handleGetStatus(params);
          
        case 'pause_game':
          return await handlePauseGame(params);
          
        case 'resume_game':
          return await handleResumeGame(params);
          
        case 'end_game':
          return await handleEndGame(params);
          
        default:
          return {
            success: false,
            message: `未知的操作类型: ${action}`,
            error: 'UNKNOWN_ACTION'
          };
      }
    } catch (error) {
      console.error(`游戏主控工具操作失败 [${action}]:`, error);
      return {
        success: false,
        message: `操作失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: error instanceof Error ? error.message : 'UNKNOWN_ERROR'
      };
    }
  },
});

/**
 * 处理开始新游戏
 */
async function handleStartGame(params: any) {
  const { gameConfig, sessionId, timestamp } = params;
  
  try {
    console.log('游戏主控：开始新游戏...', gameConfig);
    
    // 生成会话ID（如果没有提供）
    const finalSessionId = sessionId || `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    
    // 创建游戏状态
    const gameState = {
      sessionId: finalSessionId,
      phase: 'initializing',
      difficulty: gameConfig?.difficulty || 'normal',
      theme: gameConfig?.theme || '随机',
      suspectCount: gameConfig?.suspectCount || 3,
      startTime: timestamp || new Date().toISOString(),
      timeRemaining: 300, // 5分钟
      score: 0,
      discoveredClues: [],
      conversationCount: 0,
      suspectInteractions: {},
      playerProfile: gameConfig?.playerProfile || {}
    };
    
    // 协调案件生成Agent
    console.log('协调案件生成Agent...');
    const caseResult = await coordinateCaseGeneration(gameConfig);
    
    if (caseResult.success) {
      gameState.phase = 'investigation';
      gameState.caseId = caseResult.data?.case?.id;
      
      return {
        success: true,
        message: '游戏开始成功！案件已生成，开始你的调查吧！',
        data: {
          sessionId: finalSessionId,
          caseData: caseResult.data,
          gameConfig
        },
        gameState,
        sessionInfo: {
          sessionId: finalSessionId,
          createdAt: timestamp,
          status: 'active'
        },
        nextActions: [
          '查看案件详情',
          '开始与嫌疑人对话',
          '分析初始线索'
        ]
      };
    } else {
      // 使用降级方案
      console.log('案件生成失败，使用降级方案');
      const fallbackCase = generateFallbackCase(gameConfig);
      
      gameState.phase = 'investigation';
      gameState.caseId = fallbackCase.case.id;
      
      return {
        success: true,
        message: '游戏开始成功！（使用预设案件）',
        data: {
          sessionId: finalSessionId,
          caseData: fallbackCase,
          gameConfig
        },
        gameState,
        sessionInfo: {
          sessionId: finalSessionId,
          createdAt: timestamp,
          status: 'active',
          fallback: true
        },
        nextActions: [
          '查看案件详情',
          '开始与嫌疑人对话',
          '分析初始线索'
        ]
      };
    }
    
  } catch (error) {
    console.error('开始游戏失败:', error);
    return {
      success: false,
      message: `游戏开始失败: ${error instanceof Error ? error.message : '未知错误'}`,
      error: 'GAME_START_FAILED'
    };
  }
}

/**
 * 协调案件生成
 */
async function coordinateCaseGeneration(gameConfig: any) {
  try {
    // 动态导入案件生成Agent
    const { generateCase } = await import('../agents/case-generator.agent');
    
    const caseData = await generateCase(
      gameConfig?.difficulty || 'normal',
      gameConfig?.theme,
      gameConfig?.suspectCount || 3
    );
    
    return {
      success: true,
      data: caseData
    };
  } catch (error) {
    console.error('案件生成协调失败:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : '案件生成失败'
    };
  }
}

/**
 * 生成降级案件
 */
function generateFallbackCase(gameConfig: any) {
  const difficulty = gameConfig?.difficulty || 'normal';
  const theme = gameConfig?.theme || '办公室';
  const suspectCount = gameConfig?.suspectCount || 3;
  
  return {
    case: {
      id: `case-${Date.now()}`,
      title: `${theme}谋杀案`,
      description: `在${theme}发生了一起神秘的谋杀案，需要你来调查真相。`,
      location: theme,
      timeOfCrime: '上午10:30',
      victim: '张先生',
      murderWeapon: '未知',
      motive: '待查明',
      culpritId: 'suspect-1',
      difficulty,
      createdAt: new Date().toISOString()
    },
    suspects: Array.from({ length: suspectCount }, (_, i) => ({
      id: `suspect-${i + 1}`,
      name: `嫌疑人${i + 1}`,
      personality: '神秘',
      background: '背景待查',
      alibi: '声称有不在场证明',
      suspicionLevel: Math.floor(Math.random() * 10) + 1
    })),
    initialClues: [
      {
        id: 'clue-1',
        description: '现场发现的可疑物品',
        type: 'physical',
        importance: 5,
        isRevealed: true
      }
    ]
  };
}

/**
 * 处理会话管理
 */
async function handleManageSession(params: any) {
  const { sessionId, action, data } = params;
  
  console.log(`管理游戏会话 [${sessionId}]: ${action}`);
  
  // 这里应该实现会话管理逻辑
  // 暂时返回模拟数据
  return {
    success: true,
    message: `会话管理操作 ${action} 执行成功`,
    sessionInfo: {
      sessionId,
      action,
      timestamp: new Date().toISOString()
    }
  };
}

/**
 * 处理Agent协调
 */
async function handleCoordinateAgents(params: any) {
  const { targetAgent, operation, params: agentParams } = params;
  
  console.log(`协调Agent [${targetAgent}]: ${operation}`);
  
  // 这里应该实现Agent协调逻辑
  return {
    success: true,
    message: `Agent协调操作执行成功`,
    data: {
      targetAgent,
      operation,
      result: 'completed'
    }
  };
}

/**
 * 处理状态更新
 */
async function handleUpdateState(params: any) {
  const { sessionId, updates } = params;
  
  console.log(`更新游戏状态 [${sessionId}]:`, updates);
  
  return {
    success: true,
    message: '游戏状态更新成功',
    gameState: {
      sessionId,
      ...updates,
      lastUpdated: new Date().toISOString()
    }
  };
}

/**
 * 处理错误
 */
async function handleError(params: any) {
  const { sessionId, error, context } = params;
  
  console.error(`游戏错误处理 [${sessionId}]:`, error, context);
  
  return {
    success: true,
    message: '错误已处理，游戏继续',
    data: {
      errorHandled: true,
      fallbackActivated: true,
      context
    }
  };
}

/**
 * 处理获取状态
 */
async function handleGetStatus(params: any) {
  const { sessionId } = params;
  
  return {
    success: true,
    message: '状态获取成功',
    gameState: {
      sessionId,
      phase: 'investigation',
      status: 'active',
      timestamp: new Date().toISOString()
    }
  };
}

/**
 * 处理暂停游戏
 */
async function handlePauseGame(params: any) {
  const { sessionId } = params;
  
  return {
    success: true,
    message: '游戏已暂停',
    gameState: {
      sessionId,
      phase: 'paused',
      pausedAt: new Date().toISOString()
    }
  };
}

/**
 * 处理恢复游戏
 */
async function handleResumeGame(params: any) {
  const { sessionId } = params;
  
  return {
    success: true,
    message: '游戏已恢复',
    gameState: {
      sessionId,
      phase: 'investigation',
      resumedAt: new Date().toISOString()
    }
  };
}

/**
 * 处理结束游戏
 */
async function handleEndGame(params: any) {
  const { sessionId } = params;
  
  return {
    success: true,
    message: '游戏已结束',
    gameState: {
      sessionId,
      phase: 'completed',
      endedAt: new Date().toISOString()
    }
  };
}
